package org.hrqing.authorization.security;

import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;

import java.time.Duration;
import java.time.Instant;
import java.util.UUID;

/**
 * @auther Hrqing
 */
public class RandomAccessTokenGenerator implements OAuth2TokenGenerator<OAuth2AccessToken> {

    @Override
    public OAuth2AccessToken generate(OAuth2TokenContext context) {
        if (context.getTokenType() != null && context.getTokenType() == OAuth2TokenType.ACCESS_TOKEN) {
            RegisteredClient registeredClient = context.getRegisteredClient();
            TokenSettings tokenSettings = registeredClient.getTokenSettings();

            // 获取令牌有效期
            Duration tokenLifetime = tokenSettings.getAccessTokenTimeToLive();

            String tokenValue = UUID.randomUUID().toString().replaceAll("-", "");

            return new OAuth2AccessToken(
                    OAuth2AccessToken.TokenType.BEARER,
                    tokenValue,
                    Instant.now(),
                    Instant.now().plus(tokenLifetime)
            );
        }
        return null;
    }
}
